package com.masterclient.app.modules.purchase;

import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.constraint.ConstraintLayout;
import android.support.v4.widget.NestedScrollView;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.DecelerateInterpolator;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.android.arouter.launcher.ARouter;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.eoner.baselibrary.bean.goods.ProductSpecificationData;
import com.eoner.baselibrary.bean.order.ConfirmOrderData;
import com.eoner.baselibrary.bean.purchase.PurchaseProductData;
import com.eoner.baselibrary.utils.IntentUtil;
import com.eoner.baselibrary.utils.ScreenUtils;
import com.eoner.baselib.utils.toast.ToastUtil;
import com.eoner.managerlibrary.router.AroutePath;
import com.masterclient.app.BaseActivity;
import com.masterclient.app.R;
import com.masterclient.app.base.ConfirmDialog;
import com.masterclient.app.base.ProgressLoginDialog;
import com.masterclient.app.modules.purchase.adapter.PurchaseProductAdapter;
import com.masterclient.app.modules.purchase.contract.PurchaseProductContract;
import com.masterclient.app.modules.purchase.contract.PurchaseProductPresenter;
import com.masterclient.app.modules.purchase.widget.MyNestedScrollView;
import com.masterclient.app.modules.purchase.widget.PurchaseSkuDialog;
import com.masterclient.app.widget.TitlebarView;
import com.gyf.immersionbar.ImmersionBar;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * @auther hjian
 * @date 2020/9/17.
 */
public class PurchaseProductActivity extends BaseActivity<PurchaseProductPresenter> implements PurchaseProductContract.View {

    @BindView(R.id.purchase_bg)
    ImageView purchaseBg;
    @BindView(R.id.purchase_bar)
    TitlebarView purchaseBar;
    @BindView(R.id.purchase_bottom_img)
    ImageView purchaseBottomImg;
    @BindView(R.id.purchase_bottom_num)
    TextView purchaseBottomNum;
    @BindView(R.id.purchase_bottom_selected_num)
    TextView purchaseBottomSelectedNum;
    @BindView(R.id.purchase_see)
    TextView purchaseSee;
    @BindView(R.id.purchase_bottom_layout)
    ConstraintLayout purchaseBottomLayout;
    @BindView(R.id.purchase_info_layout)
    ConstraintLayout purchaseInfoLayout;
    @BindView(R.id.purchase_name)
    TextView purchaseName;
    @BindView(R.id.purchase_icon)
    ImageView purchaseIcon;
    @BindView(R.id.purchase_phone)
    TextView purchasePhone;
    @BindView(R.id.purchase_phone_call)
    ImageView purchasePhoneCall;
    @BindView(R.id.purchase_announcement_tag)
    TextView purchaseAnnouncementTag;
    @BindView(R.id.purchase_announcement_text)
    TextView purchaseAnnouncementText;
    @BindView(R.id.purchase_gift_num)
    TextView purchaseGiftNum;
    @BindView(R.id.purchase_gift_layout)
    LinearLayout purchaseGiftLayout;
    @BindView(R.id.purchase_gift_recycler)
    RecyclerView purchaseGiftRecycler;
    @BindView(R.id.purchase_dealer_layout)
    LinearLayout purchaseDealerLayout;
    @BindView(R.id.purchase_dealer_recycler)
    RecyclerView purchaseDealerRecycler;
    @BindView(R.id.purchase_scroll)
    MyNestedScrollView purchaseScroll;
    @BindView(R.id.purchase_tab_layout)
    View purchaseTabLayout;
    @BindView(R.id.purchase_tab_gift)
    TextView purchaseTabGift;
    @BindView(R.id.purchase_tab_dealer)
    TextView purchaseTabDealer;

    private int purchaseY = 0, giftY = 0;
    private boolean isSelectDealer = false;
    private PurchaseProductAdapter giftAdapter, dealerAdapter;
    private PurchaseProductData data;
    private ProgressLoginDialog progressDialog;
    private String productsJson;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_purchase_product);
        ButterKnife.bind(this);
        ImmersionBar.with(this).init();

        int statusHeight = ImmersionBar.getStatusBarHeight(this);
        purchaseBg.getLayoutParams().height = statusHeight + ScreenUtils.dp2px(84);
        ((RelativeLayout.LayoutParams)purchaseBar.getLayoutParams()).topMargin = statusHeight;

        giftAdapter = new PurchaseProductAdapter();
        purchaseGiftRecycler.setLayoutManager(new LinearLayoutManager(this){
            @Override
            public boolean canScrollVertically() {
                return false;
            }
        });
        giftAdapter.bindToRecyclerView(purchaseGiftRecycler);

        dealerAdapter = new PurchaseProductAdapter();
        purchaseDealerRecycler.setLayoutManager(new LinearLayoutManager(this){
            @Override
            public boolean canScrollVertically() {
                return false;
            }
        });
        dealerAdapter.bindToRecyclerView(purchaseDealerRecycler);

        mPresenter.getData();

        initListener();

    }

    private void initListener() {
        purchaseBar.setOnViewClick(new TitlebarView.onViewClick() {
            @Override
            public void leftClick() {
                finish();
            }

            @Override
            public void rightClick() {
                ARouter.getInstance().build(AroutePath.PURCHASE_ORDERS_ACTIVITY)
                        .withString("from_type","purchase").navigation();
            }
        });

        giftAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                ARouter.getInstance().build(AroutePath.PURCHASE_PRODUCT_DETAIL_ACTIVITY)
                        .withString("product_id",giftAdapter.getData().get(position).getProduct_id())
                        .navigation();
            }
        });

        giftAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                showProgress();
                mPresenter.getProductSpecification(giftAdapter.getData().get(position).getProduct_id());
            }
        });

        dealerAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                ARouter.getInstance().build(AroutePath.PURCHASE_PRODUCT_DETAIL_ACTIVITY)
                        .withString("product_id",dealerAdapter.getData().get(position).getProduct_id())
                        .navigation();
            }
        });

        dealerAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                showProgress();
                mPresenter.getProductSpecification(dealerAdapter.getData().get(position).getProduct_id());
            }
        });

        purchaseScroll.setOnScrollChangeListener(new NestedScrollView.OnScrollChangeListener() {
            @Override
            public void onScrollChange(NestedScrollView v, int scrollX, int scrollY, int oldScrollX, int oldScrollY) {
                if (scrollY>=purchaseY){
                    if (!isSelectDealer){
                        isSelectDealer = true;
                        setTabBg();
                    }
                }else {
                    if (isSelectDealer){
                        isSelectDealer = false;
                        setTabBg();
                    }
                }
            }
        });

        purchaseScroll.setOnScrollStatusListener(new MyNestedScrollView.OnScrollStatusListener() {
            @Override
            public void onScrollStop() {
                if (isShow) return;
                showAnim();

            }

            @Override
            public void onScrolling() {
                if (!isShow) return;
                hideAnim();
            }
        });

    }

    private boolean isShow = true;

    private void showAnim(){
        isShow = true;
        purchaseTabLayout.postDelayed(new Runnable() {
            @Override
            public void run() {
                if (isShow) {
                    purchaseTabLayout.animate().translationX(ScreenUtils.dp2px(0)).setInterpolator(new AccelerateInterpolator(3));
                }
            }
        },700);
    }

    private void hideAnim(){
        isShow = false;
        purchaseTabLayout.animate().translationX(ScreenUtils.dp2px(-32)).setInterpolator(new DecelerateInterpolator(3));
    }

    @Override
    public void showData(PurchaseProductData data) {

        this.data = data;
        //头部信息
        if (data.getSeller() != null){
            purchaseName.setText(data.getSeller().getStore_name());
            if (!TextUtils.isEmpty(data.getSeller().getMask_mobile())){
                purchasePhone.setVisibility(View.VISIBLE);
                purchasePhoneCall.setVisibility(View.VISIBLE);
                purchasePhone.setText(new StringBuffer("联系TA：").append(data.getSeller().getMask_mobile()));
            }else {
                purchasePhone.setVisibility(View.GONE);
                purchasePhoneCall.setVisibility(View.GONE);
            }
        }

        //公告
        if (!TextUtils.isEmpty(data.getNotice_text())){
            purchaseAnnouncementTag.setVisibility(View.VISIBLE);
            purchaseAnnouncementText.setVisibility(View.VISIBLE);
            purchaseAnnouncementText.setText(data.getNotice_text());
        }else {
            purchaseAnnouncementTag.setVisibility(View.GONE);
            purchaseAnnouncementText.setVisibility(View.GONE);
        }

        //礼包商品
        if (data.getGift_products() == null || data.getGift_products().size()<=0){
            purchaseGiftLayout.setVisibility(View.GONE);
            purchaseGiftRecycler.setVisibility(View.GONE);
        }else {
            purchaseGiftLayout.setVisibility(View.VISIBLE);
            purchaseGiftRecycler.setVisibility(View.VISIBLE);
            giftAdapter.setGift_icon(data.getGift_icon_url());
            giftAdapter.setNewData(data.getGift_products());
            purchaseGiftNum.setText(data.getGrand_total_num());
        }

        if (data.getNormal_products() == null || data.getNormal_products().size()<=0){
            purchaseDealerLayout.setVisibility(View.GONE);
            purchaseDealerRecycler.setVisibility(View.GONE);
        }else {
            purchaseDealerLayout.setVisibility(View.VISIBLE);
            purchaseDealerRecycler.setVisibility(View.VISIBLE);
            dealerAdapter.setGift_icon("");
            dealerAdapter.setNewData(data.getNormal_products());
        }


        purchaseInfoLayout.post(new Runnable() {
            @Override
            public void run() {
                giftY = purchaseInfoLayout.getMeasuredHeight()+ScreenUtils.dp2px(10);
                purchaseY = giftY+ScreenUtils.dp2px(64)+((data.getGift_products() == null ||
                        data.getGift_products().size()<=0?0:data.getGift_products().size())*ScreenUtils.dp2px(130));
            }
        });

        setBottom(TextUtils.isEmpty(data.getDealer_cart_num())?0:Long.parseLong(data.getDealer_cart_num()));


    }

    @Override
    public void showFailure(int type, String msg) {
        ToastUtil.showToast(msg);
        dismissProgress();
    }

    @Override
    public void showSpecificationData(ProductSpecificationData specificationData) {
        dismissProgress();
        new PurchaseSkuDialog(this, specificationData, new PurchaseSkuDialog.SkuClickListener() {
            @Override
            public void onSkuClick(PurchaseSkuDialog dialog, int type, String product_id, String num) {
                dialog.dismiss();
                if (type == 0){
                    showProgress();
                    mPresenter.addCart(product_id,num);
                }else if (type == 1){
                    showProgress();
                    productsJson = getProductsStr(product_id,num);
                    mPresenter.confirmOrder(productsJson,"2","");
                }
            }
        }).show();
    }

    @Override
    public void successAddCart(Map<String, String> map) {
        dismissProgress();
        String num = map.get("cart_num");
        setBottom(TextUtils.isEmpty(num)?0:Long.parseLong(num));
        ToastUtil.showToast("加入采购清单成功");
    }

    @Override
    public void confirmOrderSuccess(ConfirmOrderData data,String isCustody) {
        dismissProgress();
        ARouter.getInstance().build(AroutePath.ORDER_SUBMIT_ACTIVITY).withString("buy_type", "2").
                withString("buy_product", productsJson).withString("saleType", "4")
                .withSerializable("confirm_order_data", data).navigation();
    }

    private String getProductsStr(String product_id, String num) {
        JSONObject productsStr = new JSONObject();
        try {
            productsStr.put(product_id, num);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return productsStr.toString();
    }

    private void showProgress(){
        if (progressDialog == null){
            progressDialog = new ProgressLoginDialog(this);
        }
        progressDialog.show();
        progressDialog.setDesc("");
    }

    private void dismissProgress(){
        if (progressDialog != null){
            progressDialog.dismiss();
        }
    }


    @OnClick({R.id.purchase_bottom_img,R.id.purchase_see, R.id.purchase_phone_call, R.id.purchase_tab_gift, R.id.purchase_tab_dealer})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.purchase_see:
            case R.id.purchase_bottom_img:
                ARouter.getInstance().build(AroutePath.PURCHASE_SHOP_CART_ACTIVITY).navigation();
                break;
            case R.id.purchase_phone_call:
                ConfirmDialog dialog = new ConfirmDialog(this,"是否拨打电话",null,data.getSeller().getMobile(),"取消","确定","#FF6809");
                dialog.setOnChooseListerner(new ConfirmDialog.OnChooseListerner() {
                    @Override
                    public void cancel() {
                        dialog.dismiss();
                    }

                    @Override
                    public void confirm() {
                        IntentUtil.toPhoneApp(PurchaseProductActivity.this,data.getSeller().getMobile());
                        dialog.dismiss();
                    }
                });
                dialog.show();
                break;
            case R.id.purchase_tab_gift:
                if (!isSelectDealer) return;
//                isSelectDealer = false;
                purchaseScroll.fling(0);
                purchaseScroll.smoothScrollTo(0,giftY);
                break;
            case R.id.purchase_tab_dealer:
                if (isSelectDealer) return;
//                isSelectDealer = true;
                purchaseScroll.fling(0);
                purchaseScroll.smoothScrollTo(0,purchaseY);
                break;
        }
    }

    /**
     * 悬浮的tab样式
     */
    private void setTabBg() {
        purchaseTabDealer.setBackgroundResource(isSelectDealer?R.drawable.purchase_tab_selected:R.drawable.purchase_tab_default);
        purchaseTabGift.setBackgroundResource(!isSelectDealer?R.drawable.purchase_tab_selected:R.drawable.purchase_tab_default);
        purchaseTabDealer.setTextColor(Color.parseColor(isSelectDealer ? "#FFFFFF" : "#FF6809"));
        purchaseTabGift.setTextColor(Color.parseColor(!isSelectDealer ? "#FFFFFF" : "#FF6809"));
        purchaseTabDealer.getLayoutParams().width = ScreenUtils.dp2px(isSelectDealer?32:28);
        purchaseTabGift.getLayoutParams().width = ScreenUtils.dp2px(!isSelectDealer?32:28);
        purchaseTabDealer.setTextSize(isSelectDealer?13:12);
        purchaseTabGift.setTextSize(!isSelectDealer?13:12);
    }

    private void setBottom(long num){
        if (num>0){
            purchaseBottomNum.setText(String.valueOf(num));
            purchaseBottomNum.setVisibility(View.VISIBLE);
        }else {
            purchaseBottomNum.setVisibility(View.GONE);
        }
        purchaseBottomSelectedNum.setText(new StringBuffer("已选").append(num).append("件商品").toString());
    }
}
